package com.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@Component
@ServerEndpoint("/ws/{id}")
public class WebSocketServer {

    @Value("${id}")
    private String connectId;

    /**与某个客户端的连接会话，需要通过它来给客户端发送数据,
     * 也可以通过session().close();主动关闭连接
     * */
    private Session session;

    /**
     * 业务标识
     */
    private String id;

    /**
     * 一个Map,其实就是一个容器
     */
    public static Map<String, WebSocketServer> socketServerMap = new ConcurrentHashMap<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) {
        log.info("连接成功"+id);
        this.session = session;
        this.id = id;
        socketServerMap.put(id,this);
    }

    /**
     * 连接关闭,调用的方法
     */
    @OnClose
    public void onClose() {
        socketServerMap.remove(this.id);
        log.info("连接关闭"+id);
    }

    /**
     * 错误回调
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error(error.toString());
    }

    /**
     * 接收前端推送的消息
     */
    @OnMessage
    public void onMessage(Session session, String msg) {

        log.info("接受到的消息:"+msg);
    }


    /**
     * 服务器主动推送消息
     */
    public void sendMessage(String message) {
        try {
            WebSocketServer webSocketServer = socketServerMap.get(connectId);
            if (webSocketServer!=null){
                this.session=webSocketServer.session;
            }
            if (this.session!=null){
                log.info("开始发送");
                this.session.getBasicRemote().sendText(message); // 给前端发送消息！
                log.info("发送成功");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

